package com.boyla.speech2text

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import android.content.ComponentName
import android.content.pm.PackageManager.MATCH_ALL
import android.speech.RecognitionService
import android.provider.Settings.Secure


class MainActivity : AppCompatActivity() {

    var mSpeechRecognizer: SpeechRecognizer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (!SpeechRecognizer.isRecognitionAvailable(this)) {
            tv.text = "语音识别不可用"
            return
        }
        val serviceComponent = Secure.getString(getContentResolver(),
                "voice_recognition_service")
        // 当前系统内置语音识别服务
        val component = ComponentName.unflattenFromString(serviceComponent)
        // 内置语音识别服务是否可用
        var isRecognizerServiceValid = false
        var currentRecognitionCmp: ComponentName? = null
// 查找得到的 "可用的" 语音识别服务
        val list = getPackageManager().queryIntentServices(Intent(RecognitionService.SERVICE_INTERFACE), MATCH_ALL)

        if (list != null && list!!.size != 0) {
            for (info in list!!) {
                println("\t" + info.loadLabel(getPackageManager()) + ": "
                        + info.serviceInfo.packageName + "/" + info.serviceInfo.name)

                // 这里拿系统使用的语音识别服务和内置的语音识别比较，如果相同，OK我们直接直接使用
                // 如果相同就可以直接使用mSpeechRecognizer =              SpeechRecognizer.createSpeechRecognizer(context);来创建实例，因为内置的可以使用
                if (info.serviceInfo.packageName == component?.getPackageName()) {
                    isRecognizerServiceValid = true
                    break
                } else {
                    // 如果服务不同，说明 内置服务 和 系统使用 不是同一个，那么我们需要使用系统使用的
                    // 因为内置的系统不用，我们用了也没有用
                    currentRecognitionCmp = ComponentName(info.serviceInfo.packageName, info.serviceInfo.name)
                }
            }
        }
        println("==== currentRecognitionCmp null: " + (currentRecognitionCmp == null))
        mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this, currentRecognitionCmp)

        mSpeechRecognizer?.setRecognitionListener(object : RecognitionListener {
            override fun onReadyForSpeech(params: Bundle?) {
                println("==== onReadyForSpeech")
            }

            override fun onRmsChanged(rmsdB: Float) {
                println("==== onRmsChanged")
            }

            override fun onBufferReceived(buffer: ByteArray?) {
                println("==== onBufferReceived")
            }

            override fun onPartialResults(partialResults: Bundle?) {
                println("==== onPartialResults")
            }

            override fun onEvent(eventType: Int, params: Bundle?) {
                println("==== onEvent")
            }

            override fun onBeginningOfSpeech() {
                println("==== onBeginningOfSpeech")

            }

            override fun onEndOfSpeech() {
                println("==== onEndOfSpeech")
            }

            override fun onError(error: Int) {
                println("==== onError")
            }

            override fun onResults(results: Bundle?) {
                println("==== onResults")
                var key = SpeechRecognizer.RESULTS_RECOGNITION
                var mResult = results?.getStringArrayList(key)
                if (mResult != null) {
                    for (item in mResult) {
                        tvContent.text = item
                    }
                }

            }

        })

        tv.setOnClickListener {
            // 启动服务需要一个 Intent
            var mRecognitionIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
            mRecognitionIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
            mRecognitionIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
            mRecognitionIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3)
// mLocale 是一个语音种类，可以根据自己的需求去设置
            mRecognitionIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.CHINA);

// 开始语音识别 结果在 mSpeechRecognizer.setRecognitionListener(this);回调中
            mSpeechRecognizer?.startListening(mRecognitionIntent)
        }
    }
}
